package com.jyh.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jyh.dao.PermissionMapper;
import com.jyh.dao.UserMapper;
import com.jyh.entity.MyUser;
import com.jyh.entity.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author JYH
 * @version 1.0
 * @date 2023/1/3 19:07
 */
@Service
public class UserService implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserMapper userMapper;
    @Resource
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据账户查询用户的信息
        QueryWrapper<MyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        MyUser myUser = userMapper.selectOne(queryWrapper);
        if (myUser!=null){
            //查询具有的权限
            List<Permission> permissions = permissionMapper.findByUserId(myUser.getUserid());
            List<SimpleGrantedAuthority> authorities = permissions.stream().map(item -> new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
            return new User(username,myUser.getUserpwd(),authorities);
        }
        return null;

    }
}
